#include "recbox.h"
#include "ui_recbox.h"
#include "recboxitem.h"

#include <math.h>

RecBox::RecBox(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RecBox)
    , row(1)
    , col(4)
{
    ui->setupUi(this);
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data, int row)
{
    if(row == 2)
    {
        // 如果是两⾏，说明当前RecBox是主界⾯上的supplyMusicBox
        this->row = row;
        this->col = 8;
    }
    else
    {
        // 否则：只有⼀⾏，为主界⾯上recMusicBox
        ui->recListDown->hide();
    }

    imageList = data;

    //默认显示第0组
    currentIndex = 0;

    // 计算总共有⼏组图⽚，ceil表⽰向上取整
    count = ceil(imageList.size() / col);

    // 向recBox控件里面添加recBoxItem
    createRecBoxItem();
}

void RecBox::createRecBoxItem()
{
    //删除RecBox内部的之前放入的元素
    //通过它的父类的find Children()函数找到RecBoxItem类型的几个孩子
    QList<RecBoxItem*> listUp = ui->recListUp->findChildren<RecBoxItem*>();
    for(auto &child : listUp)
    {
        ui->recListUpHLayout->removeWidget(child);
        delete child;
    }

    QList<RecBoxItem*> listDown = ui->recListDown->findChildren<RecBoxItem*>();
    for(auto &child : listDown)
    {
        ui->recListDownHLayout->removeWidget(child);
        delete child;
    }

    //今日为你推荐: row = 1, col = 4;
    //你的音乐补给: row = 2, col = 8.
    // 创建RecBoxItem对象，往RecBox中添加
    int index = 0;
    for(int i = currentIndex * col; i < col + currentIndex * col; ++i)
    {
        RecBoxItem* item = new RecBoxItem();

        QJsonObject obj = imageList[i].toObject();
        item->setText(obj.value("text").toString());
        item->setImage(obj.value("path").toString());

        if(index >= col / 2 && row == 2)
        {
            ui->recListDownHLayout->addWidget(item);
        }
        else
        {
            ui->recListUpHLayout->addWidget(item);
        }

        index++;
    }
}

void RecBox::on_btUp_clicked()
{
    //点击按钮之后,需要显示下一组照片,如果已经是第0组照片,让它显示最后一组照片
    currentIndex--;
    if(currentIndex < 0)
    {
        currentIndex = count - 1;
    }

    createRecBoxItem();
}

void RecBox::on_btDown_clicked()
{
    //点击按钮之后,需要显示下一组照片,如果已经是最后组照片,让它显示第0组照片
    currentIndex++;
    if(currentIndex >= count)
    {
        currentIndex = 0;
    }

    createRecBoxItem();
}

